import { createApp } from 'vue';
import ElementPlus from 'element-plus';
import zhCn from 'element-plus/dist/locale/zh-cn.mjs';
import DialogShow from '@/components/DialogShow.vue';
import { ElMessage, ElMessageBox  } from 'element-plus';

export default {
  success(message) {
    ElMessage({
      message,
      type: 'success',
    });
  },

  error(message) {
    ElMessage({
      message,
      type: 'error',
    });
  },

  alert(message, title = '提示') {
    ElMessageBox.alert(message, title, {
      confirmButtonText: '确定'
    })
  },

  confirm(message, title = '提示') {
    return ElMessageBox.confirm(
      message,
      title,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
  },

  /**
   * 模态弹窗，并打开组件内容
   * @param component
   * @param data 传递的数据
   * @param options
   * {
   *   title: '标题',
   *   confirmButtonText: '确定按钮文案',
   *   cancelButtonText: '取消按钮文案',
   *   beforeClose: '异步关闭回调函数，点击调用接口完成后关闭'
   * }
   */
  show(component, data, options = {
    title: '',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    beforeClose() {
      return true;
    }
  }) {
    data = data || {};

    return new Promise((resolve, reject) => {
      let dialogAppEl = document.createElement('div');
      document.body.appendChild(dialogAppEl);

      let dialogApp = createApp(DialogShow, {
        ...options,
        pageData: {
          ...data
        },
        closed: () => {
          dialogApp.unmount();
          document.body.removeChild(dialogAppEl);
        },
        confirm: d => resolve(d)
      });

      dialogApp.use(ElementPlus, {
        locale: zhCn
      });
      dialogApp.component('dialog-show-inner', component.default);
      dialogApp.mount(dialogAppEl);
    });
  },
};
